import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref(null)
  const token = ref('')
  const isLoggedIn = ref(false)

  // 初始化状态
  const initializeFromLocalStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      user.value = JSON.parse(storedUser)
      isLoggedIn.value = true
    }
  }

  // 设置用户信息
  const setUser = (userData) => {
    user.value = {
      username: userData.username,
      nickname: userData.nickname,
      roles: userData.roles
    }
    token.value = userData.token
    isLoggedIn.value = true
  }

  // 清除用户信息
  const clearUser = () => {
    user.value = null
    token.value = ''
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 检查是否有特定角色
  const hasRole = (role) => {
    if (!user.value || !user.value.roles) return false
    return user.value.roles.includes(role)
  }

  return {
    user,
    token,
    isLoggedIn,
    initializeFromLocalStorage,
    setUser,
    clearUser,
    hasRole
  }
}) 